package org.example.memora.handler;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.util.Map;

@Component
public class WebSocketDisconnectHandler implements ApplicationListener<SessionDisconnectEvent> {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
        Map<String, Object> attributes = accessor.getSessionAttributes();

        if (attributes != null) {
            String userId = (String) attributes.get("userId");
            String communityId = (String) attributes.get("communityId");

            if (userId != null && communityId != null) {
                String key = "chat:online:" + communityId;
                redisTemplate.opsForSet().remove(key, userId);
                //System.out.println("下线：" + userId);
            }
        }
    }
}

